package application.common.cron4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.cron4j.ITask;

import application.common.model.User;
import application.common.render.HttpClientResult;
import application.common.util.HttpUtil;
import application.common.util.ShiroUtil;
import net.sf.json.JSONObject;

public class FprTask implements ITask{
	private final Log log = Log.getLog(getClass());
	private boolean isEnd=true;
	public void run() {
		if(isEnd) {
			isEnd=false;
			if(ShiroUtil.getConfig()!=null && !StrKit.isBlank(ShiroUtil.getConfig().getSynURL())) {
				try {
					
					int pageNumber=1;
					int pageSize=5;
					
					while(true) {
						String sqlExceptSelect = " FROM "+User.TABLE_NAME+" ";
						Page<User> pages=User.dao.paginate(pageNumber, pageSize,"select * " ,sqlExceptSelect);
						if(pages==null || pageNumber>pages.getTotalPage()) {
							break;
						}
						pageNumber++;
						List<User> users=pages.getList();
						if(users!=null && users.size()>0) {
							Map<String, String> params =new HashMap<String,String>();
							params.put("rows", JsonKit.toJson(users));
							params.put("cabinetId", ShiroUtil.getAuth());
							HttpClientResult httpClientResult=HttpUtil.doPost(String.format("%s/api/cab/saveFpr", ShiroUtil.getConfig().getSynURL()), params);
							if(httpClientResult==null) {
								break;
							}
							if(httpClientResult.getCode()!=200) {
								break;
							}
							String content=httpClientResult.getContent();
							if(StrKit.isBlank(content)) {
								break;
							}
							JSONObject jsonObject=JSONObject.fromObject(content);
							if(jsonObject==null) {
								break;
							}
							if(jsonObject.has("code")) {
								int code=jsonObject.getInt("code");
								if(code!=200) {
									break;
								}
								log.info("指纹上传成功：【"+pageNumber+"】");
							}else {
								log.info("指纹上传异常！");
								break;
							}
						}else {
							log.info("暂无指纹需要同步！");
							break;
						}
					}
					isEnd=true;
				}catch (Exception e) {
					log.info("指纹同步异常！",e);
					isEnd=true;
				}
			}
			isEnd=true;
		}
	}

	public void stop() {
	}

}
